package com.example.mybatisdemo.mapper;

import com.example.mybatisdemo.model.UserInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;

//不用五大注解，使用mapper之后，mabatis就会告诉Spring，把对象交给Spring管理
//来自于ibatis，是mybatis的前身
@Mapper
public interface UserInfoMapper {


    /**
     * 结果映射
     * 方法一：对字段进行重命名
     * */
    //完成了数据库的访问，select表示查询语句
    @Select("select id,username,password,age,gender,phone," +//企业开发中用几个取几个
            " delete_flag as deleteFlag,create_time as createTime," +
            " update_time as updateTime from userinfo")
    //方法实现
    List<UserInfo> selectAll();//方法声明


    /**结果映射
     * 方法二：使用Results注解
     * @return
     */
    @Results(id = "BaseMap", value = {
            @Result(column = "delete_flag", property = "deleteFlag"),
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "update_time", property = "updateTime"),

    })
    @Select("select * from userinfo")//方法实现
    List<UserInfo> selectAll2();//方法声明



    /***
     * 结果映射
     * 方法三：使用配置的方式，自动转驼峰
     * @return
     */
    @Select("select * from userinfo")
    List<UserInfo> selectAll3();




    //传递参数，如果只有一个参数，名称可以为任意的，
    @ResultMap(value = "Base userinfo")
    @Select("select * from userinfo where id= #{id}")
    UserInfo selectOne(Integer id);


    @ResultMap(value = "BaseMap")
    @Select("select * from userinfo where username= #{username}")
    List<UserInfo> selectByName(String username);


    //对id进行重命名通过@Param
    @Select("select * from userinfo where id= #{userId}")
    UserInfo selectOne2(@Param("userId") Integer id);



    //返回自增ID
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into userinfo (username,password,age,gender,phone)" +
            " values (#{username},#{password},#{age},#{gender},#{phone})")
    Integer insert(UserInfo userInfo);

    //对Insert的参数进行重命名
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into userinfo (username,password,age,gender,phone)" +
            " values (#{userInfo.username},#{userInfo.password}," +
            " #{userInfo.age},#{userInfo.gender},#{userInfo.phone})")
    Integer insert2(@Param("userInfo") UserInfo userInfo);


    //删除操作
    @Delete("DELETE FROM userinfo WHERE id=#{id}")
    void delect(Integer id);

    //改操作
    @Update("UPDATE userinfo SET username=#{username} WHERE id=#{id}")
    Integer update(UserInfo userInfo);

    /**
     * 排序
     * @param sort
     * @return
     * */
    @Select("select * from userinfo order by id ${sort}")
    List<UserInfo> selectUserBySort(String sort);



    /**
     * 模糊查询
     * @param username
     * @return
     * */

    @Select("select * from userinfo where username like CONCAT(`%`,#{username},`%`")
    List<UserInfo> selectUserByLike(String username);
}
